package com.styytech.dadabao.ui.login;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.loopj.android.http.RequestParams;
import com.styytech.dadabao.DadaApplication;
import com.styytech.dadabao.R;
import com.styytech.dadabao.api.requestresult.RegistResult;
import com.styytech.dadabao.api.response.AbstractResponseResult;
import com.styytech.dadabao.api.templates.HttpRequest;
import com.styytech.dadabao.base.BaseActivity;
import com.styytech.dadabao.constant.ConstantsServerUrl;
import com.styytech.dadabao.exception.ArgumentsException;
import com.styytech.dadabao.exception.RequestException;
import com.styytech.dadabao.utils.CommonUtils;
import com.styytech.dadabao.utils.Md5Utils;
import com.styytech.dadabao.utils.NumberUtil;
import com.styytech.dadabao.utils.SpUser;
import com.styytech.dadabao.widge.dialog.CustomLoadingDialog;

/**
 * 注册界面，密码加密一次后上传到服务器
 */
@ContentView(R.layout.activity_register)
public class RegisterActivity extends BaseActivity {

    /**
     * 验证码
     */
    public final int REQUEST_CODE_AUTH_CODE = 1;
    /**
     * 验证验证码
     */
    public final int REQUEST_CODE_CHECKING_AUTH_CODE = 2;
    /**
     * 注册
     */
    public final int REQUEST_CODE_REGISTER = 3;
    /**
     * 验证手机号是否已注册
     */
    public final int REQUEST_CODE_CHECK_PHONE = 4;

    /**
     * 手机号
     */
    @ViewInject(R.id.et_number)
    private EditText et_number;
    /**
     * 密码
     */
    @ViewInject(R.id.et_password)
    private EditText et_password;
    /**
     * 确认密码
     */
    @ViewInject(R.id.et_passwordOk)
    private EditText et_passwordOk;
    /**
     * 验证码
     */
    @ViewInject(R.id.et_auth_code)
    private EditText et_auth_code;
    /**
     * 获取验证码按钮
     */
    @ViewInject(R.id.tv_auth_code)
    private TextView tv_auth_code;
    /**
     * 提示语：短信已发送至188****1234
     */
    @ViewInject(R.id.tv_number_tips)
    private TextView tv_number_tips;
    /**
     * 注册按钮
     */
    @ViewInject(R.id.bt_register)
    private Button bt_register;
    /**
     * 下一步
     */
    @ViewInject(R.id.bt_next)
    private Button bt_next;
    /**
     * 输入手机号
     */
    @ViewInject(R.id.llyt_phone_number)
    private LinearLayout llyt_phone_number;
    /**
     * 输入注册密码
     */
    @ViewInject(R.id.llyt_regist_password)
    private LinearLayout llyt_regist_password;


    /*上下文*/
    Context context;
    CustomLoadingDialog mdlg;//loading框

    private String phoneNumTemp = "";//手机号预留
    private String phoneNum = "";// 手机号
    private String password = null;// 密码
    private String passwordOk = null;// 确认密码
    private String auchuCode = null;// 验证码

    /**
     * 计时器
     */
    private TimeCount timeCount = null;
    /**
     * 0：还未计时
     * 1：正在计时：
     * -1：
     */
    private boolean isTimeCount = false;// false：还未计时或计时结束，true：正在计时

    private boolean isComplete = false;// false:不符合注册条件，true:符合注册条件

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = this;
        initView();
    }

    private void initView() {
        DadaApplication.addActivity(this);
        setTopBar("用户注册", View.VISIBLE);
        /*隐藏设置密码布局*/
        llyt_phone_number.setVisibility(View.VISIBLE);
        llyt_regist_password.setVisibility(View.GONE);
        /*eidtText输入监听*/
        et_password.addTextChangedListener(registEdit);
        et_passwordOk.addTextChangedListener(registEdit);
        et_auth_code.addTextChangedListener(registEdit);
        et_number.addTextChangedListener(phoneNumberEdit);

    }

    @Override
    protected void reloadBtnOnclick() {
        super.reloadBtnOnclick();
    }

    @OnClick({R.id.tv_auth_code, R.id.bt_register, R.id.bt_next})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_auth_code: // 重新获取验证码
                getAuthCode();
                break;
            case R.id.bt_register:// 立即注册
                regist();
                break;
            case R.id.bt_next:// 下一步
                phoneNumTemp = et_number.getText().toString().trim();
                if (!phoneNumTemp.equals(phoneNum)) {
                    et_auth_code.setText("");
                    et_password.setText("");
                    et_passwordOk.setText("");
                }
                bt_next.setBackgroundResource(R.drawable.btn_disable_selector);
                checkPhoneRegisted();
                break;
        }
    }

    @Override
    protected void baseBackClick() {
        if (llyt_phone_number.getVisibility() == View.VISIBLE) {
            finish();
        } else {
            llyt_phone_number.setVisibility(View.VISIBLE);
            llyt_regist_password.setVisibility(View.GONE);
        }
    }

    @Override
    public void onBackPressed() {
//        super.onBackPressed();
        if (llyt_phone_number.getVisibility() == View.VISIBLE) {
            finish();
        } else {
            llyt_phone_number.setVisibility(View.VISIBLE);
            llyt_regist_password.setVisibility(View.GONE);
        }
    }

    public void getAuthCode() {
        /*获取用户输入的手机号*/
        phoneNum = et_number.getText().toString().trim();
        /*手机号过滤*/
        if (phoneNum.isEmpty()) {
            //手机号码不能为空
            toast(getResources().getString(R.string.number_no_empty));
            return;
        } else if (NumberUtil.checkNumber(phoneNum).getType() == NumberUtil.PhoneType.INVALIDPHONE) {
            //请填写正确手机号码
            toast(getResources().getString(R.string.number_to_right));
            return;
        }

        /*如果未开始计时或者计时结束，才能再次获取验证码*/
        if (!isTimeCount) { // 发送
            // 显示对话框
            mdlg = CommonUtils.getCustomLoadingDialog(context, mdlg, "获取验证码", true);
            mdlg.show();
            /*获取验证码接口*/
            String url = ConstantsServerUrl.getCheckCode();
            RequestParams params = new RequestParams();
            params.put("mobileNumber", phoneNum);
            //获取验证码
            requestAuthCode(REQUEST_CODE_AUTH_CODE, url, params);
        } else {
            //短信已发送
            CommonUtils.showToastMsg(context, "" + getResources().getString(R.string.sms_had_sent));
        }
    }

    /**
     * 验证手机号是否已注册
     */
    public void checkPhoneRegisted() {
        /*获取手机号*/
        phoneNum = et_number.getText().toString().trim();
        /*对验证码异常过滤*/
        if (phoneNum.isEmpty()) {
            //验证码不能为空
            toast(getResources().getString(R.string.number_no_empty));
            return;
        } else if (NumberUtil.checkNumber(phoneNum).getType() == NumberUtil.PhoneType.INVALIDPHONE) {
            //验证码长度为6位
            toast(getResources().getString(R.string.number_to_right));
            return;
        }
        /*验证手机号是否已注册接口*/
        String url = ConstantsServerUrl.getCheckUserCdUrl();
        /*设置参数*/
        RequestParams params = new RequestParams();
        params.put("mobile", phoneNum);
        /*请求校验手机号是否已注册*/
//        requestAuthCode(REQUEST_CODE_CHECK_PHONE, url, params);
        //获取验证码
        RegistResult requestResult = new RegistResult(REQUEST_CODE_CHECK_PHONE, responseResult1);
        try {
            new HttpRequest(this).doPost(requestResult, url, params);
        } catch (ArgumentsException e) {
            Log.i("INFO", "1e:" + e);
            e.printStackTrace();
        } catch (RequestException e) {
            Log.i("INFO", "2e:" + e);
            e.printStackTrace();
        }
    }

    /**
     * 注册
     */
    private void regist() {
        /*获取用户输入的值*/
        phoneNum = et_number.getText().toString().trim();
        password = et_password.getText().toString().trim();
        passwordOk = et_passwordOk.getText().toString().trim();
        auchuCode = et_auth_code.getText().toString().trim();

        /*条件过滤*/
        if (phoneNum.isEmpty()) {
            //手机号码不能为空
            toast(getResources().getString(R.string.number_no_empty));
            return;
//        } else if (phoneNum.length() != 11) {
        } else if (NumberUtil.checkNumber(phoneNum).getType() == NumberUtil.PhoneType.INVALIDPHONE) {
            //请填写正确手机号码
            toast(getResources().getString(R.string.number_to_right));
            return;
        } else if (password.isEmpty()) {
            //密码不能为空
            toast(getResources().getString(R.string.pwd_no_empty));
            return;
        } else if (password.length() < 6) {
            //密码不能少于6位
            toast(getResources().getString(R.string.pwd_too_low));
            return;
        } else if (password.length() > 30) {
            //密码长度不能大于30位
            toast(getResources().getString(R.string.pwd_too_much));
            return;
        } else if (passwordOk.isEmpty()) {
            //确认密码不能为空
            toast(getResources().getString(R.string.pwd_ensure_no_empty));
            return;
        } else if (!password.equals(passwordOk)) {
            //两次密码不一致
            toast(getResources().getString(R.string.pwd_no_agree));
            return;
        } else if (auchuCode.isEmpty()) {
            //验证码不能为空
            toast(getResources().getString(R.string.code_no_empty));
            return;
        }
        registRquest();

    }

    /**
     * 注册请求
     */
    private void registRquest() {
        // 显示对话框
        mdlg = CommonUtils.getCustomLoadingDialog(context, mdlg, "立即注册", true);
        mdlg.show();
        /*注册请求的Url接口*/
        String url = ConstantsServerUrl.getUserRegisterUrl();
        /*请求参数类*/
        RequestParams params = new RequestParams();
        /*密码加密*/
        String mD5Pass = Md5Utils.hash(password);
        /*参数设置*/
        params.put("mobile", phoneNum);
        params.put("password", mD5Pass);
        params.put("checkCode", auchuCode);
        //注册请求
        /*请求校验手机号是否已注册*/
        requestAuthCode(REQUEST_CODE_REGISTER, url, params);
    }

    /**
     * 请求校验验证码
     *
     * @param rquestCode 请求码
     * @param url        请求的url接口
     * @param params     请求的参数
     */
    public void requestAuthCode(int rquestCode, String url, RequestParams params) {
        //获取验证码
        RegistResult requestResult = new RegistResult(rquestCode, responseResult);
        try {
            new HttpRequest(this).doPost(requestResult, url, params);
        } catch (ArgumentsException e) {
            Log.i("INFO", "1e:" + e);
            e.printStackTrace();
        } catch (RequestException e) {
            Log.i("INFO", "2e:" + e);
            e.printStackTrace();
        }
    }

    /**
     * 启动界面
     *
     * @param cls 需要启动的界面类
     */
    private void startMainActivity(Class<?> cls) {
        Intent intent = new Intent(context, cls);
        startActivity(intent);
        finish();
    }

    /**
     * 提示消息
     *
     * @param str 需要提示的消息
     */
    private void toast(String str) {
        Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
    }


    /**
     * 注册请求结果处理
     */
    AbstractResponseResult responseResult = new AbstractResponseResult() {

        @Override
        public void executeSuccess(Object object) {
            CommonUtils.closeDialog(mdlg);
            switch ((int) object) {
                case REQUEST_CODE_AUTH_CODE://验证码
                    /*开始计时*/
                    timeCount = new TimeCount(60000, 1000);
                    timeCount.start();
//                    CommonUtils.showToastMsg(context, "获取验证码成功！");
                     /*提示语*/
                    String phone = phoneNum.substring(0, 3) + "****" + phoneNum.substring(7, 11);
                    tv_number_tips.setText("短信已发送至" + phone);
                    break;
                case REQUEST_CODE_CHECKING_AUTH_CODE://验证验证码
                    CommonUtils.showToastMsg(context, "验证验证码");
                    break;
                case REQUEST_CODE_REGISTER://注册
                    SpUser.setUserName(context, "");
                    CommonUtils.showToastMsg(context, "注册成功！");
                    startMainActivity(LoginActivity.class);
                    break;
                case REQUEST_CODE_CHECK_PHONE://手机号未注册，进入注册界面
                     /*显示隐藏的界面*/
                    llyt_phone_number.setVisibility(View.GONE);
                    llyt_regist_password.setVisibility(View.VISIBLE);
                    break;
            }

        }

        @Override
        public void executeError(String message, int errorCode) {
            CommonUtils.showToastMsg(context, "" + message);
            CommonUtils.closeDialog(mdlg);
        }

        @Override
        public void HttpError(String message, int errorCode) {
            CommonUtils.closeDialog(mdlg);
            CommonUtils.showToastMsg(context, "" + message);
        }
    };
    /**
     * 检查手机号是否注册请求
     */
    AbstractResponseResult responseResult1 = new AbstractResponseResult() {

        @Override
        public void executeSuccess(Object object) {
            switch ((int) object) {

                case REQUEST_CODE_CHECK_PHONE://手机号未注册，进入注册界面
                    toast("该手机号已被注册");
                    break;
            }

        }

        @Override
        public void executeError(String message, int errorCode) {
            bt_next.setBackgroundResource(R.drawable.btn_common_selector);
             /*显示隐藏的界面*/
            llyt_phone_number.setVisibility(View.GONE);
            llyt_regist_password.setVisibility(View.VISIBLE);
             /*提示语*/
            tv_number_tips.setText("请先获取验证码");
        }

        @Override
        public void HttpError(String message, int errorCode) {
            CommonUtils.closeDialog(mdlg);
            CommonUtils.showToastMsg(context, "" + message);
        }
    };


    /**
     * 倒计时
     */
    class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);//参数依次为总时长,和计时的时间间隔
        }

        /**
         * 计时完毕时触发
         */
        @Override
        public void onFinish() {
            isTimeCount = false;
            tv_auth_code.setText("重新发送");
//            tv_auth_code.setClickable(true);
            tv_auth_code.setTextColor(getResources().getColor(R.color.main_red));
        }

        /**
         * 计时过程显示
         *
         * @param millisUntilFinished
         */
        @Override
        public void onTick(long millisUntilFinished) {
            isTimeCount = true;
//            tv_auth_code.setClickable(false);
            tv_auth_code.setTextColor(getResources().getColor(R.color.gray));
            tv_auth_code.setText(millisUntilFinished / 1000 + "秒后重试");
        }
    }

    /**
     * 手机号输入监听
     */
    private TextWatcher phoneNumberEdit = new TextWatcher() {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {
//            Log.i("123", "phoneNumberEdit-start:" + start + before);
            if (et_number.length() == 11) {
                bt_next.setBackgroundResource(R.drawable.btn_common_selector);
//                bt_next.setClickable(true);
            } else {
                bt_next.setBackgroundResource(R.drawable.btn_disable_selector);
//                bt_next.setClickable(false);
            }
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    };
    /**
     * 验证码输入监听
     */
    private TextWatcher registEdit = new TextWatcher() {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {
//            Log.i("123", "phoneNumberEdit-start:" + start + before);

            if (et_auth_code.length() > 0 && et_passwordOk.length() >= 6 && et_password.length() >= 6) {
                isComplete = true;
            } else {
                isComplete = false;
            }
            if (isComplete) {
                bt_register.setBackgroundResource(R.drawable.btn_common_selector);
//                bt_register.setClickable(true);
            } else {
                bt_register.setBackgroundResource(R.drawable.btn_disable_selector);
//                bt_register.setClickable(false);
            }
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    };
}
